from django.shortcuts import render, HttpResponse
from app.models import Case
import jieba
from fuzzywuzzy import fuzz,process

def pretreatment(text):#数据预处理
    # 1、分词处理
    text = jieba.cut(text.strip())
    # 2、去除停用词
    # 创建一个停用词列表
    stopwords = [line.strip() for line in
                 open('D:\pythonCode\MedicalProject\\app\data\stopwords.txt', encoding='UTF-8').readlines()]
    sentence = ''
    # 去停用词
    for word in text:
        if word not in stopwords:
            if word != '\t':
                sentence += word
                sentence += " "
    return sentence

# Create your views here.
def do_search(request):
    if request.method=="POST":
        #1、获取搜索页面提交的描述字符
        description=request.POST.get("description")
        #2、文本预处理
        sentence = pretreatment(description)
        #3、获取数据库中的全部信息
        data_list = Case.objects.all()
        #4、创建数据字典
        data_dict={}
        #5、计算相似度
        for data in data_list:
            name = data.name
            symbols = data.symptom
            symbols = pretreatment(symbols)
            value = fuzz.token_sort_ratio(sentence, symbols)
            if(value!=0):
                data_dict[name]=value

        #6、根据字典键值进行排序
        Dict = sorted(data_dict.items(), key=lambda x:x[1], reverse = True)
        for key in Dict:
            print(key[0], key[1])

        #7、将字典中的病症名称进行过滤,先遍历字典再遍历数组，顺序不能乱，要按照字典中排列好的顺序显示
        Data=[]
        for key in Dict:
            for data in data_list:
                if data.name==key[0]:
                    Data.append(data)

        #for d in Data:
        #   print(d)
        #8、将数组中的值返回给列表页面
        return render(request, 'get_list.html', {"data_list": Data})
    return render(request,'do_search.html')


def get_details(request,uname):
    data_details = Case.objects.all().filter(name=uname).first()
    return render(request,'get_details.html',{"data_details":data_details})

